/*
 * Duplicate Detector Copyright (C) 2010 Marco Biscaro <marcobiscaro2112@gmail.com>
 * 
 * This file is part of Duplicate Detector.
 *
 * Duplicate Detector is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Duplicate Detector is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Duplicate Detector.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.duplicatedetector.i18n;

import java.net.URL;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import com.googlecode.duplicatedetector.Constants;
import com.googlecode.duplicatedetector.util.Logger;

/**
 * Main internationalization class.
 * 
 * @author Marco Biscaro
 */
public final class Messages implements Constants {

	private static final Logger LOGGER = new Logger(Messages.class);
	private static Locale locale = Locale.getDefault();
	private static ResourceBundle resource = loadResourceBundle();

	private Messages() {
		// can not instantiate
	}

	public static String getMessage(String key) {
		try {
			return resource.getString(key);
		} catch (MissingResourceException e) {
			LOGGER.warning("No message value for key " + key);
			return "*" + key + "*";
		}
	}

	/**
	 * Just an alias to {@link #getMessage(String)}
	 */
	public static String _(String key) {
		return getMessage(key);
	}

	public static Locale getLocale() {
		return locale;
	}

	public static void setLocale(Locale locale) {
		LOGGER.debug("Changing locale to " + locale);
		Messages.locale = locale;
		resource = loadResourceBundle();
	}

	private static ResourceBundle loadResourceBundle() {
		ResourceBundle.clearCache();
		return ResourceBundle.getBundle(I18N_FOLDER + I18N_FILE_PREFIX, locale);
	}

	public static URL getHelp(String name) {
		StringBuilder path = new StringBuilder(DOCS_FOLDER);
		path.append(name);
		if (!name.equals(LICENSE_FILE)) { // license file is not under i18n
			path.append('_');
			path.append(locale.getLanguage());
			path.append('_');
			path.append(locale.getCountry());
		}
		path.append(DOCS_EXTENSION);
		return Messages.class.getResource(path.toString());
	}

}
